package com.tianqu.tms.www.financia.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;

import com.tianqu.tms.core.base.Logger;
import com.tianqu.tms.core.base.TmsController;
import com.tianqu.tms.core.base.TxController;
import com.tianqu.tms.core.base.UserContext;
import com.tianqu.tms.core.exception.TmsException;
import com.tianqu.tms.core.exception.TransactionException;
import com.tianqu.tms.core.security.TmsUserProfile;
import com.tianqu.tms.core.util.CopyFile;
import com.tianqu.tms.core.util.ImageUtils;
import com.tianqu.tms.core.util.Registry;
import com.tianqu.tms.core.util.StringUtil;
import com.tianqu.tms.core.util.TmsConstants;
import com.tianqu.tms.core.webservice.weichat.api.MobileMessage;
import com.tianqu.tms.core.webservice.weichat.api.PullingExecutor;
import com.tianqu.tms.core.webservice.weichat.api.rpc.TransferDataSyn1304Bo;
import com.tianqu.tms.dto.TmsFinanciaDto;
import com.tianqu.tms.entity.CarImage;
import com.tianqu.tms.entity.Sequence;
import com.tianqu.tms.entity.TmsFinancial;
import com.tianqu.tms.entity.User;
import com.tianqu.tms.www.financia.viewhelper.FinanciaCompanyInputViewHelper;

public class FinanciaCompanyCreationResultController extends TmsController {
	private Logger logger = Logger.getLogger(FinanciaCompanyCreationResultController.class);

	private static final String IMGLIST = "imgList";// 图片list
	private static final String SYSPATH = "sysPath";//
	public static final String FLOORSFLAG = "floorsflag";

	@Override
	public void execute(UserContext uc) throws Exception {
		logger.debug(this.getClass().getName() + "#execute was called.");
		TxController controller = TxController.getTxController();

		// 添加事务提交异常捕获
		try {
			controller.begin();
			// 从uc中获取会员信息
			FinanciaCompanyInputViewHelper viewhelp = (FinanciaCompanyInputViewHelper) uc.getAttribute(TmsConstants.VIEWHELP);
			uc.removeAttribute(TmsConstants.VIEWHELP);// 清空uc
			
			TmsFinancial financial = TmsFinancial.getInstance();
			TmsFinanciaDto dto = new TmsFinanciaDto();
			//view to dto
			BeanUtils.copyProperties(dto, viewhelp); 
			// 从mapList中取出图片信息set到viewhelp中
			List<CarImage> imgList = new ArrayList<CarImage>();
			if (uc.getAttribute(IMGLIST) != null) {
				imgList = (List<CarImage>) uc.getAttribute(IMGLIST);
			}
			if (imgList != null) {
				for (int i = 0; i < imgList.size(); i++) {
					CarImage entity = (CarImage) imgList.get(i);
					if (entity.getImgKey().equals(TmsConstants.ONE)) {
						dto.setMemberZipCode(entity.getImgPath());
					}
					if (entity.getImgKey().equals(TmsConstants.TWO)) {
						dto.setCardPhoto(entity.getImgPath());
					}
					if (entity.getImgKey().equals(TmsConstants.THREE)) {
						dto.setOrgPhoto(entity.getImgPath());
					}
					if (entity.getImgKey().equals(TmsConstants.FIVE)) {
						dto.setBusinessPhoto(entity.getImgPath());
					}
				}
			}				
			//
			TmsUserProfile profile = uc.getUserProfile();
			dto.setUpdateUserId(profile.getUniqueId());
			dto.setInsertUserId(profile.getUniqueId());
			 
			//将image图片信息放到服务器上
			File outFile = null;
			File inFile = null;
			String sysPath = (String) uc.getAttribute(SYSPATH);
			sysPath = sysPath.replace("/tmsweb", TmsConstants.BLANK);

			try {
				if(dto.getOrgPhoto()!=null && !"".equals(dto.getOrgPhoto()))
				{
					inFile = new File(sysPath+dto.getOrgPhoto());
					outFile = new File(ImageUtils.getImageDirectoryPath(Registry.getConfig(TmsConstants.UPLOAD_FINANCIA_PATCH_KEY)+dto.getFinanciaId()+"/")+dto.getFinanciaId()+"_1.jpg");
					CopyFile.copy(inFile, outFile);	
					dto.setOrgPhoto(imgPath(dto.getOrgPhoto(), dto.getFinanciaId(), "1"));
				}
				
				if(dto.getBusinessPhoto()!=null && !"".equals(dto.getBusinessPhoto()))
				{
					inFile = new File(sysPath+dto.getBusinessPhoto());
					outFile = new File(ImageUtils.getImageDirectoryPath(Registry.getConfig(TmsConstants.UPLOAD_FINANCIA_PATCH_KEY)+dto.getFinanciaId()+"/")+dto.getFinanciaId()+"_2.jpg");
					CopyFile.copy(inFile, outFile);	
					dto.setBusinessPhoto(imgPath(dto.getBusinessPhoto(), dto.getFinanciaId(), "2"));
				}
				
				if(dto.getCardPhoto()!=null && !"".equals(dto.getCardPhoto()))
				{
					inFile = new File(sysPath+dto.getCardPhoto());
					outFile = new File(ImageUtils.getImageDirectoryPath(Registry.getConfig(TmsConstants.UPLOAD_FINANCIA_PATCH_KEY)+dto.getFinanciaId()+"/")+dto.getFinanciaId()+"_3.jpg");
					CopyFile.copy(inFile, outFile);	
					dto.setCardPhoto(imgPath(dto.getCardPhoto(),dto.getFinanciaId(), "3"));
				}
				
				if(dto.getMemberZipCode()!=null && !"".equals(dto.getMemberZipCode()))
				{
					inFile = new File(sysPath+dto.getMemberZipCode());
					outFile = new File(ImageUtils.getImageDirectoryPath(Registry.getConfig(TmsConstants.UPLOAD_FINANCIA_PATCH_KEY)+dto.getFinanciaId()+"/")+dto.getFinanciaId()+"_5.jpg");
					CopyFile.copy(inFile, outFile);	
					dto.setMemberZipCode(imgPath(dto.getMemberZipCode(), dto.getFinanciaId(), "5"));
				}
			} catch (Exception e) {
				logger.error("",e);
			}
			
			User user = new User();
			if(dto.getId() > 0) {
				financial.updateTmsFinancia(dto);
				user.updatePasswordByUserId(viewhelp.getPassword(),viewhelp.getUserId(),profile.getUniqueId());
			}else {
				Sequence sequence = Sequence.getInstance();
				dto.setFinanciaId(sequence.getSerial(9));
				financial.insertTmsFinancia(dto);
				user = setUserFormView(user, viewhelp);
				user.setUpdateUserId(profile.getUniqueId());
				user.setInsertUserId(profile.getUniqueId());
				user.setUcId("11");// 默认为系统会员
				user.saveUserInfo(user,4);
			}
			
			uc.removeAttribute(IMGLIST);
			logger.debug(this.getClass().getName() + "#execute was completed.");
			controller.commit();
			
			//微信同步
			MobileMessage message = new MobileMessage();
			message.putValue("financiaId", dto.getFinanciaId());
			message.setMessage("金融公司添加调用接口失败,商户ID为#financiaId#");
			TransferDataSyn1304Bo api = new TransferDataSyn1304Bo();
			api.setMobileMessage(message);
			api.setFinanciaId(dto.getFinanciaId());
			api.setFinanciaName(dto.getFinanciaName());
			api.setShortName(dto.getShortName());
			api.setRealNamePy(dto.getRealNamePy());
			api.setContactOwner(dto.getContactOwner());
			api.setContactPhone(dto.getContactPhone());
			api.setUserId(dto.getUserId());
			api.setMarketNo(TmsConstants.MARKET_NO);
			PullingExecutor.getInstance().submit(api);
		} catch (Exception e) {
			try {
				controller.rollback();
			} catch (TransactionException e1) {
				throw new TmsException(TmsException.DB_TXCRROR, e1);
			}
			// 系统异常
			if (e instanceof TmsException) {
				throw e;
			}
			throw new TmsException(TmsException.DB_TXCRROR, e);
		}

	}
	/**
	 * 处理存入数据库中的图片路径
	 */
	private String imgPath(String path,String id,String imgKey){
		return ImageUtils.getImageUrl(Registry.getConfig(TmsConstants.UPLOAD_FINANCIA_PATCH_KEY) +id+"/"+id+"_"+imgKey+".jpg") ;	
	}	

	/**
	 * 将viewhelp中的数据set到user中进行添加
	 * 
	 */
	private User setUserFormView(User entity, FinanciaCompanyInputViewHelper view) {

		entity.setLoginId(view.getUserId());
		entity.setRealName(view.getFinanciaName());
		entity.setPassword(view.getPassword());
		return entity;
	}
}
